
var controllers = angular.module('controllers',[]);

controllers.controller('IndexController',['$routeParams','$rootScope','$scope','$timeout','commonApi',function ($routeParams,$rootScope,$scope,$timeout,commonApi){
	$scope.class = {
		chart_type: 'line',
		show_edit: false
	};

	$scope.data = {
 		fieldDate: '',
 		chart_x: [],
 		chart_y: [],
 		chartType: [],
 		xData: [],
 		mychart: '',
 		pieseries: [],
 		lineseries: [],
 		barseries: [],
 		mapseries:[],
 		legendData: [],
 		searchData: [],
 		searchList: [],
 		gauViewList:['SHOW_MAIN_MONITOR']
 	};

 	$scope.event = {
 		switchChartType: function(index,type,e){
 			$(e.target).parent().addClass('active');
 			$(e.target).parents('li').siblings().find('a').removeClass('active');
 			$scope.class.chart_type = type;
 			//$scope.initEcharts();
 			//$scope.event.preview();
			
			var $this = $(this);
			if( type=='gauge' ){
				$(".jsFd").show();
				
				$(".jsFd").find('input[type=range]').each(function(){
					var $tc = $(this);
					$tc.off('change').on('change',function(){
						//console.log($scope);
						$scope.convertData(function(){
							$scope.event.preview();
						});
					})
				})
				
				$(".jsFd").find('input[type=number]').each(function(){
					var $tc = $(this);
					$tc.off('change').on('change',function(){
						//console.log($scope);
						$scope.convertData(function(){
							$scope.event.preview();
						});
					})
				})
			}else{
				$(".jsFd").hide();
			}
			
 			$scope.convertData(function(){
				$scope.event.preview();
			});
 		},
 		closeThisDialog: function(){
 			$(".ngdialog").fadeOut();
 		},
 		showDialog: function(){
 			$("#ngdialog").fadeIn();
 		},
 		getFilterRange: function(){
 			if($('.filter_range').hasClass('hide')){
 				$('.filter_range').removeClass('hide');
 			}else{
 				$('.filter_range').addClass('hide');
 			}
 		},
 		addData: function(){
 			$("#dataDialog").fadeIn();
 		},
 		preview:function(){
			var chart_y_temp = $scope.data.chart_y;
			var chart_x_temp = $scope.data.chart_x;
			//console.log(chart_y_temp,chart_x_temp);
			if(temp_option.temp.length<1){
				temp_option.temp.push({});
			}
			commonApi.previewPost({
				modelId:modelId,
				viewName:$('#vw').val(),
				chartname:$('.chart-title .input-text-block').val(),
				option:JSON.stringify(temp_option.temp[0]),
				chart_x:JSON.stringify(chart_x_temp),
				chart_y:JSON.stringify(chart_y_temp),
				chart_type:$scope.class.chart_type,
				fenduan1:$('#range1').val(),
				fenduan2:$('#range2').val(),
				yuqi:$('#range3').val()
			},function(backdata){
				if(backdata.success){
					var url = backdata.data[0];
					url=baseUrl+url;
					var _w = ($scope.data.chart_type=='gauge')?400:600;
					$('#chart').empty().append("<iframe src='"+url+"' style='border:0;outline:0;width:"+_w+"px;height:400px'></iframe>");
					//window.open(url);
				}
			})
 		}
    };

    $scope.$on('$viewContentLoaded', function (d, data) {
    	//1.获取数据库列表
    	commonApi.getModelList(function(back){
    		if(back.success){
    			//console.log(back);
    			var _dbhtml = [];
    			$.each(back.data,function(ii,ee){
    				_dbhtml.push("<option value='"+ee.id+"'>"+ee.modelName+"</option>");
    			})
    			_dbhtml.push("<option value='excel'>Excel数据库</option>");
    			$("#db").empty().append(_dbhtml.join(''));
    			//2.绑定数据库切换事件
    			$(".title-desc select#db").off("change").on("change",function(){
    				var $thisdb = $(this);
    				modelId = $thisdb.val();
    				if(modelId==0){
	    				$(".title-desc select#vw").empty();
	    				commonApi.resetPage($scope);
    					return false;
    				}
    				//3.获取视图
    				//视图列表
			    	commonApi.getViewList(function(back){
			    		if(back.success){
			    			if(back.data.length<1){
			    				$(".title-desc select#vw").empty();
	    						commonApi.resetPage($scope);
		    					return false;
			    			}
			    			var _html = "";
			    			$.each(back.data,function(i,e){
			    				_html = _html + "<option value='"+e.viewName+"'>"+e.viewNameCN+"</option>";
			    			})
			    			$(".title-desc select#vw").empty().append(_html);
			    			commonApi.getFieldList(null, function(data2){
			    				$scope.$apply(function() {
			    					$scope.data.fieldDate = data2.field;
			    				});
			    			});
			
			    			//视图
			    			$(".title-desc select#vw").off("change").on("change",function(){
								commonApi.resetPage($scope);
			    				commonApi.getFieldList(null, function(data2){
			    					//console.log(data2.field);
			    					$scope.$apply(function() {
			    						$scope.data.fieldDate = data2.field;
			    					});
			    				});
			    				var $this = $(this);
			    				if( $.inArray($this.val(),$scope.data.gauViewList) > -1 ){
			    					//$(".jsVd").hide();
			    					$(".jsFd").show();
			    					
			    					$(".jsFd").find('input[type=range]').each(function(){
			    						var $tc = $(this);
			    						$tc.off('change').on('change',function(){
			    							//console.log($scope);
			    							$scope.convertData(function(){
												$scope.event.preview();
											});
			    						})
			    					})
			    					
			    					$(".jsFd").find('input[type=number]').each(function(){
			    						var $tc = $(this);
			    						$tc.off('change').on('change',function(){
			    							//console.log($scope);
			    							$scope.convertData(function(){
												$scope.event.preview();
											});
			    						})
			    					})
			    				}else{
			    					//$(".jsVd").show();
			    					$(".jsFd").hide();
			    				}
			    			})
			    			
			    			//发布
			    			$("a[chart-fabu='1']").off("click").on("click",function(){
			    				if(temp_option.temp.length>0){
			    					var chart_y_temp = $scope.data.chart_y;
			    					var chart_x_temp = $scope.data.chart_x;
			    					//console.log(chart_y_temp,chart_x_temp);
			    					commonApi.fabuPost({
			    						modelId:modelId,
			    						viewName:$('#vw').val(),
			    						chartname:$('.chart-title .input-text-block').val(),
			    						option:JSON.stringify(temp_option.temp[0]),
			    						chart_x:JSON.stringify(chart_x_temp),
			    						chart_y:JSON.stringify(chart_y_temp),
			    						chart_type:$scope.class.chart_type,
			    						fenduan1:$('#range1').val(),
			    						fenduan2:$('#range2').val(),
										yuqi:$('#range3').val()
			    					},function(backdata){
			    						if(backdata.success){
			    							var url = backdata.data[0];
			    							url=baseUrl+url;
			    							window.open(url);
			    						}
			    					})
			    				}else{
			    					console.log(temp_option);
			    					alert('error : none option');
			    				}
			    			})
			    		}
			    	})
    			})
    			$(".title-desc select#db").prepend("<option value='0'>------选择数据库------</option");
    			$(".title-desc select#db option:eq(0)").attr('selected','selected');
    		}
    	})
    	
    	
    	/*commonApi.getFieldData({},function(data){
			console.log(data);
			$scope.data.fieldDate = data.field;
			$scope.data.searchList = $scope.data.fieldDate[0].data;
		});*/
    	
		var uri = function (uri) {
            return (typeof __url === 'function') ? __uri(uri) : uri;
        };
    	$scope.data.chartType = [
    		{
    			type: 'line',
    			icon: uri('img/line.png'),
    			title: '条形图'
    		},
    		{
    			type: 'bar',
    			icon: uri('img/bar.png'),
    			title: '柱状图'
    		},
    		{
    			type: 'pie',
    			icon: uri('img/pie.png'),
    			title: '饼图'
    		},
    		{
    			type: 'map',
    			icon: uri('img/map.png'),
    			title: '地图'
    		},
    		{
    			type: 'gauge',
    			icon: uri('img/gau.png'),
    			title: '仪表盘'
    		},
            {
                type: 'gauge2',
                icon: uri('img/gau.png'),
                title: '仪表盘'
            }
    	];

  		$scope.stopDragField = function(){
			$scope.convertData(function(){
				$scope.event.preview();
			});
			/*$timeout(function() {
				if($scope.data.searchData[0]){
					$("#ngdialog").fadeIn();
					$(".no-filter").fadeOut();
					$scope.class.show_edit = true;
				}
			},500);*/
		}

  		$scope.convertData = function(callback){
  			$timeout(function() {
				if($scope.data.chart_x[0]){
					$scope.data.xData = $scope.data.chart_x[0].data;
				}
				if($scope.data.lineseries){
					$scope.data.lineseries = [];
				}
				if($scope.data.barseries){
					$scope.data.barseries = [];
				}
				if($scope.data.pieseries){
					$scope.data.pieseries = [];
				}
				if($scope.data.mapseries){
					$scope.data.mapseries = [];
				}
				for (var i = 0; i < $scope.data.chart_y.length; i++) {
					$scope.data.legendData.push($scope.data.chart_y[i].title);
					$scope.data.lineseries.push({
						name: $scope.data.chart_y[i].title,
			            type: 'line',
			            data: $scope.data.chart_y[i].data
					});
					
					$scope.data.barseries.push({
						name: $scope.data.chart_y[i].title,
			            type: 'bar',
			            data: $scope.data.chart_y[i].data
					});
					
					$scope.data.mapseries.push({
						name: $scope.data.chart_y[i].title,
			            type: 'map',
			            data: $scope.data.chart_y[i].data
					});
					
					var userName = [], userValue = [] ,pieData = [];
						userName = $scope.data.chart_x[0]?$scope.data.chart_x[0].data:[];
						userValue = $scope.data.chart_y[i].data;
					for(var j = 0; j< userName.length; j++){
						pieData.push({
							value: userValue[j],
							name: userName[j]
						});
					}
					$scope.data.pieseries.push({
						name: $scope.data.chart_y[i].title,
			            type: 'pie',
			            radius: ['50%', '70%'],
			            label: {
			                normal: {
			                    show: false,
			                    position: 'center'
			                },
			                emphasis: {
			                    show: true,
			                    textStyle: {
			                        fontSize: '30',
			                        fontWeight: 'bold'
			                    }
			                }
			            },
			            data: pieData
					});
				}
				
				if($scope.data.chart_x != '' && $scope.data.chart_y != ''){
					//$scope.initEcharts();
					if(typeof(callback)=="function"){
						callback();
					}
				}
			}, 500);
  		}


		$scope.initEcharts = function(){
			$scope.data.mychart = echarts.init(document.getElementById("chart"),'macarons');
			if($scope.class.chart_type == 'line'){
				option = {
					tooltip: {
				        trigger: 'axis',
				        axisPointer :{
				        	type:"shadow"
				        }
				    },
					legend: {
						top: '5%',
				        data: $scope.data.legendData
				    },
				    xAxis: {
				        type: 'category',
				        boundaryGap: false,
				        data: $scope.data.xData
				    },
				    yAxis: {
				        type: 'value'
				    },
				    series:$scope.data.lineseries
				};
				temp_option.temp = [option];
				$scope.data.mychart.setOption(option);		
			}else if($scope.class.chart_type == 'bar'){
				option = {
					tooltip: {
				        trigger: 'axis',
				        axisPointer :{
				        	type:"shadow"
				        }
				    },
					legend: {
						top: '5%',
				        data: $scope.data.legendData
				    },
				    xAxis: {
				        type: 'category',
				        data: $scope.data.xData,
				        axisTick: {
			                alignWithLabel: true
			            }
				    },
				    yAxis: {
				        type: 'value'
				    },
				    series:$scope.data.barseries
				};
				temp_option.temp = [option];
				$scope.data.mychart.setOption(option);
			}else if($scope.class.chart_type == 'pie'){
				option = {
				    legend: {
				        orient: 'vertical',
				        itemWidth: 5,
				        itemHeight: 5,
				        x: 'right',
				        align: 'left',
				        data: $scope.data.xData
				    },
				    series: $scope.data.pieseries
				};
				temp_option.temp = [option];
				$scope.data.mychart.setOption(option);
			}else if($scope.class.chart_type == 'map'){
				option = {
					tooltip: {
				    	show:true,
				        trigger: 'item',
				        textStyle:{
	                    	fontSize:14
	                  	}
				    },
				    visualMap: {
				    	type:'continuous',
				        min: 80,
				        max: 550,
				        left: '10%',
        				bottom: '10%',
        				text: ['高','低'],
				        show :true,
				        inRange :{
				        	color:['#61aceb','#7abdef','#a0d9f6','#c7eefb','#dbfcfe'].reverse()
				        }
				    },
				    series: [
				        {
				            name: '江苏',
				            type: 'map',
				            map: 'jiangsu',
				            selectedMode :'single',
				            label: {
				                normal: {
				                    show: true,
				                    textStyle:{
				                    	fontSize:14
				                    }
				                },
				                emphasis: {
				                    show: true,
				                    textStyle:{
				                    	fontSize:16
				                    }
				                }
				            },
				            data:[
				            	{name: '苏州市',value:545.4 },
				            	{name: '南京市',value:337.8 },
				            	{name: '无锡市',value:274.9 },
				            	{name: '南通市',value:189 },
				            	{name: '徐州市',value:168.8 },
				            	{name: '盐城市',value:161.1 },
				            	{name: '常州市',value:145.6 },
				            	{name: '淮安市',value:120 },
				            	{name: '宿迁市',value:107.1 },
				            	{name: '泰州市',value:104.1 },
				            	{name: '连云港市',value:100.9 },
				            	{name: '镇江市',value:94.1 },
				            	{name: '扬州市',value:83.7 }
				            ]
				        }
				    ]
				    //series: $scope.data.mapseries
				};
				temp_option.temp = [option];
				$scope.data.mychart.setOption(option);
			}
		}
	});
}]);

controllers.controller('SaveController',['$routeParams','$rootScope','$scope','$timeout','commonApi',function ($routeParams,$rootScope,$scope,$timeout,commonApi){
	$scope.class = {
        showType: 1,
	};

	$scope.data = {
 		fieldDate: '',
 		legendData: [],
 		xData: [],
 		barseries: [],
 		mychart: '',
 		theadData: []
 	};

 	$scope.event = {
 		selectShowType: function(index){
            $scope.class.showType = index;
            if(index == 2){
            	$scope.insetChart();
            }
        }
 	};

	$scope.$on('$viewContentLoaded', function (d, data) {
		commonApi.getFieldData({},function(data){
			$scope.data.fieldDate = data.field;
		});
		
		$timeout(function() {
			$scope.data.xData = $scope.data.fieldDate[0].data;
			for(i = 1; i< $scope.data.fieldDate.length; i++){
				$scope.data.legendData.push($scope.data.fieldDate[i].title);
				$scope.data.barseries.push({
					name: $scope.data.fieldDate[i].title,
		            type: 'bar',
		            data: $scope.data.fieldDate[i].data
				});
			}
			var tbData = [];
			for(j = 0; j< $scope.data.fieldDate.length; j++){
				$scope.data.theadData.push($scope.data.fieldDate[j].title);
				tbData.push($scope.data.fieldDate[j].data);
			}
			$scope.data.tbodyData = new Array();
			for(var k=0;k<tbData[0].length;k++){
				$scope.data.tbodyData[k] = new Array();
				for(var m=0;m<tbData[k].length+2;m++){
					if(tbData[m]&&tbData[m][k]){
						$scope.data.tbodyData[k].push(tbData[m][k]);
					}
				}
			}
			// console.log($scope.data.tbodyData);
		},500);

		$scope.insetChart =  function(){
			$timeout(function() {
				$scope.data.myChart = echarts.init(document.getElementById('chart'),'macarons');
				option = {
					tooltip: {
				        trigger: 'axis',
				        axisPointer :{
				        	type:"shadow"
				        }
				    },
					legend: {
						top: '5%',
				        data: $scope.data.legendData
				    },
				    xAxis: {
				        type: 'category',
				        data: $scope.data.xData,
				        axisTick: {
			                alignWithLabel: true
			            }
				    },
				    yAxis: {
				        type: 'value'
				    },
				    series:$scope.data.barseries
				};
				temp_option.temp = [option];
				$scope.data.myChart.setOption(option);
			},300);
			
		}
	});
}]);	




